package cn.rkylin.oms.push.controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.push.adapter.PushAdapter;
import cn.rkylin.oms.push.adapter.PushAdapterFactory;
import cn.rkylin.oms.push.request.PushRefundAppr;
import cn.rkylin.oms.push.request.PushRefundBatchAgree;
import cn.rkylin.oms.push.request.PushRefundRefuse;
import cn.rkylin.oms.push.request.PushReturnGoodsAgree;
import cn.rkylin.oms.refund.service.IRefundService;
import cn.rkylin.oms.refund.vo.RefundVO;
import cn.rkylin.oms.system.shop.domain.Shop;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;

@Controller
@RequestMapping("/pushRefund")
public class PushRefundController extends ApolloController {

    private static final Log logger = LogFactory.getLog(PushRefundController.class);
    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    /**
     * 店铺服务层
     */
    @Autowired
    private IShopService shopService;

    @Autowired
    private IRefundService refundService;

    /**
     * 批量同意退款接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushRefundBatchAgree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushRefundBatchAgree(@RequestBody PushRefundBatchAgree request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcRefundCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushRefundBatchAgree(shop, request.getEcRefundCode(), request.getCode());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 拒绝退款接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushRefundRefuse", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushRefundRefuse(@RequestBody PushRefundRefuse request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcRefundCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushRefundRefuse(shop, request.getEcRefundCode(), request.getRefuseMessage(), request.getRefuseReasonId(),
                    request.getRefusePath());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 卖家同意退货接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushReturnGoodsAgree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushReturnGoodsAgree(@RequestBody PushReturnGoodsAgree request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcRefundCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushReturnGoodsAgree(shop, request.getEcRefundCode(), request.getName(), request.getAddress(),
                    request.getPost(), request.getTel(), request.getMobile(), request.getRemark(), request.getSellerAddressId());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 审核退款单接口
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/pushRefundAppr", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> pushRefundAppr(@RequestBody PushRefundAppr request) throws Exception {
        Map<String, Object> resultMap = null;
        PushAdapter pushAdapter = null;
        Shop shop = null;
        try {
            // 验证请求参数
            resultMap = pushDataValidate(request.getShopId(), request.getEcRefundCode());
            // 如果有错误信息
            if (resultMap.containsKey("success") && resultMap.containsKey("msg")) {
                return resultMap;
            }
            // 获取shop
            shop = (Shop) resultMap.get("shop");
            // 获取pushAdapter
            pushAdapter = (PushAdapter) resultMap.get("pushAdapter");

            resultMap = pushAdapter.pushRefundAppr(shop, request.getEcRefundCode(), request.getErpStatus());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            resultMap.put("success", "n");
            resultMap.put("msg", ex.getMessage());
        }
        return resultMap;
    }

    /**
     * 请求参数验证
     * 
     * @throws Exception
     */
    private Map<String, Object> pushDataValidate(String shopId, String ecRefundCode) throws Exception {

        Map<String, Object> resultMap = new HashMap<>();

        // shopId 没有的场合
        if (StringUtils.isEmpty(shopId)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        }
        
        // ecRefundCode 没有的场合
        if (StringUtils.isEmpty(ecRefundCode)) {
            resultMap.put("success", "n");
            resultMap.put("msg", "数据不存在");
            return resultMap;
        }
        
//        // 根据ecItemCode取得ecitem的主键
//        List<String> listEcItem = getEcRefund(shopId, ecRefundCode);
//        if (listEcItem == null || listEcItem.size() <= 0) {
//            resultMap.put("success", "n");
//            resultMap.put("msg", "数据不存在");
//            return resultMap;
//        }
        
        Shop shop = getShop(shopId);
        if (shop == null || StringUtils.isEmpty(shop.getEnable()) || StringUtils.isEmpty(shop.getDeleted())) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺不存在");
            return resultMap;
        } else if (shop.getEnable().equalsIgnoreCase("n")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺未启用");
            return resultMap;
        } else if (shop.getDeleted().equalsIgnoreCase("y")) {
            resultMap.put("success", "n");
            resultMap.put("msg", "店铺已删除");
            return resultMap;
        }
        
        // 如果是子店铺
        if(StringUtils.isNotEmpty(shop.getParentShop())){
            Shop shopParent = getShop(shop.getParentShop());
            shop.setApiUrl(shopParent.getApiUrl());
            shop.setAppKey(shopParent.getAppKey());
            shop.setAppSecret(shopParent.getAppSecret());
            shop.setSessionKey(shopParent.getSessionKey());
        }
        
        resultMap.put("shop", shop);
        PushAdapter pushAdapter = PushAdapterFactory.getPushAdapter(shop);
        if (pushAdapter == null) {
            resultMap.put("success", "n");
            resultMap.put("msg", "推送失败");
            return resultMap;
        }
        resultMap.put("pushAdapter", pushAdapter);
        return resultMap;
    }

    private String getShopIdByRefund(List<String> listEcRefund) {
        String shopId = "";
        try {

            // for (int i = 0; i < listEcItem.size(); i++) {
            // ItemVO itemVo = itemService.getEcItemById(listEcItem.get(i));
            // shopId = itemVo.getShopId();
            // break;
            // }

            if (listEcRefund.size() > 0) {
                RefundVO refundVo = refundService.getEcRefundById(listEcRefund.get(0));
                shopId = refundVo.getShopId();
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return shopId;
    }

    /**
     * 根据shopId取得shop对象
     * 
     * @param shopid
     * @return
     */
    private ShopVO getShop(String shopid) {
        ShopVO shopVO = null;
        try {
            if (StringUtils.isNotBlank(shopid)) {
                shopVO = shopService.getShopById(shopid);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            shopVO = null;
        }
        return shopVO;
    }

    /**
     * 根据ecRefundCode取得EcRefund对象
     * 
     * @param ecItemCode
     * @return
     */

    private List<String> getEcRefund(String shopId, String ecRefundCode) {
        List<String> listEcItem = new ArrayList<String>();
        try {
            // 如果是批量操作的场合
            if (ecRefundCode.indexOf(",") != -1) {
                ecRefundCode = ecRefundCode.replace("[", "").replace("]", "");
                for (String strTemp : ecRefundCode.split(",")) {
                    RefundVO parameter = new RefundVO();
                    RefundVO refundVO = null;
                    parameter.setShopId(shopId);
                    parameter.setEcRefundCode(strTemp);
                    List<RefundVO> list = refundService.findByRefundCode(parameter);
                    if (list != null) {
                        for (int i = 0; i < list.size(); i++) {
                            refundVO = list.get(i);
                            listEcItem.add(refundVO.getEcRefundId());
                        }
                    }
                }
            } else {
                RefundVO parameter = new RefundVO();
                RefundVO refundVO = null;
                parameter.setShopId(shopId);
                parameter.setEcRefundCode(ecRefundCode);
                List<RefundVO> list = refundService.findByRefundCode(parameter);
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        refundVO = list.get(i);
                        listEcItem.add(refundVO.getEcRefundId());
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            listEcItem = null;
        }
        return listEcItem;
    }
}
